var mainCustomerIds = sessionStorage.getItem("mainCustomerId")
//指定正常商品
function designatedCommodity () {
    $(".dataTables_wrapper").css({
        display: "inline"
    });
    $.ajax({
        url: root.member.productAppointRulelistPage,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify({
            pageNum: 1,
            pageSize: 20,
            "mainCustomerId": mainCustomerIds,
            "spuCode": $("#spuCode").val(),
            "skuCode": $("#skuCode").val(),
            "skuName": $("#spuName").val()

        }),
        success: function (result) {
            designatedCommoditylist(result);
            $('.M-box3').pagination({
                pageCount: result.data.pageCount,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        url: root.member.productAppointRulelistPage,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType: 'json',
                        contentType: "application/json",
                        data: JSON.stringify({
                            pageNum: api.getCurrent(),
                            pageSize: 20,
                            "mainCustomerId": mainCustomerIds,
                            "spuCode": $("#spuCode").val(),
                            "skuName": $("#spuName").val()

                        }),
                        success: function (result) {
                            designatedCommoditylist(result);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！', 2000);
        }
    });
}
/*表格渲染*/
var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];

function designatedCommoditylist (data) {
    console.log(data)
    dataSource.splice(0, dataSource.length);//清空数组
    if (data.data.data != "") {
        $.each(data.data.data, function (i, field) {
            var rowData = new Array();
            rowData.push(field.spuCode);
            rowData.push(field.skuCode);
            rowData.push(field.skuName);
            rowData.push(field.operateUserName);
            rowData.push(field.updateTime);
            rowData.push(field.productAppointRuleId);
            dataSource.push(rowData);
        });
    }
    initDataTable(dataSource);

    function initDataTable (dataSource) {
        var dttable = $('#designateddatatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#designateddatatable").DataTable({
            "order": [[1, "desc"]],
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": [5, 10, 25, 50],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
                "sProcessing": "<img src='./loading.gif' />",
            },
            data: dataSource,
            columnDefs: [{
                "visible": true,
                "targets": 0
            },
            {
                "render": function(data, type, row, meta) {
                    var val = '<span style="text-align: left;"><td><input class="spuId" type="checkbox" name="spuId" data-code="' + row[0] + '" data-name="' + row[1] + '" value = "' + row[4] + '">' + row[0] + '</td></span>';
                    return val;
                },
                "targets": 0
            },
            {
                "render": function(data, type, row, meta) {
                    var val = row[2]
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 1
            },
            {
                "render": function(data, type, row, meta) {
                    var val = row[1]
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 2
            },
            {
                "render": function(data, type, row, meta) {
                    var val = row[3]
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 3
            },
            {
                "render": function(data, type, row, meta) {
                    var val = row[4]
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 4
            },

            {
                "render": function(data, type, row) {
                    var val = '<span class=""><a onclick="detaildelete(\'' + row[5] + '\',\'' + row[0] + '\',\'' + row[2] + '\')">移除</a></span>';
                    return val;
                },
                "targets": 5
            }
        ],
            "fnInitComplete": function (oSettings, json) {
                setBtnDis(0, $("#productManage"));
                $("#datatable").on("change", '.spuId', function () {
                    var num = $(".shun").find("input[type=checkbox]:checked").length;
                    setBtnDis(num, $("#productManage"));
                });

            }
        });
    };
    //权限控制函数
    power()
}
//单个删除
function detaildelete (id, code, name) {

    var productAppointRuleDtos = {}
    var productAppointRuleDtosarr = [];
    productAppointRuleDtos = {
        productAppointRuleId: id,
        spuCode: code,
        spuName: name
    }
    productAppointRuleDtosarr.push(productAppointRuleDtos);
    $.ajax({
        url: root.member.productAppointRuledeleteBatchByIds,
        contentType: "application/json;charset=UTF-8",
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        data: JSON.stringify({
            "operateUserId": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
            "operateUserName": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
            "mainCustomerId": mainCustomerIds,
            "productAppointRuleDtos": productAppointRuleDtosarr
        }),
        success: function (data) {
            if (data.errorCode == 0) {
                $.Huimodalalert('移除成功！', 2000);
                designatedCommodity();
            } else {
                $.Huimodalalert(data.msg, 2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！', 2000);
        }
    })
};
//批量删除
function batchdelete () {

    var productAppointRuleDtos = {}
    var productAppointRuleDtosarr = [];
    var spuIdArr = document.getElementsByName('spuId');
    for (var i = 0; i < spuIdArr.length; i++) {
        if (spuIdArr[i].checked == true) {
            productAppointRuleDtos = {
                productAppointRuleId: spuIdArr[i].value,
                spuCode: $(spuIdArr[i]).attr("data-code"),
                spuName: $(spuIdArr[i]).attr("data-name")
            }
            productAppointRuleDtosarr.push(productAppointRuleDtos)
        }

    }
    if (productAppointRuleDtosarr == '') {
        $.Huimodalalert('请选择批量选择数据！', 2000);
        return false;
    }
    $.ajax({
        url: root.member.productAppointRuledeleteBatchByIds,
        contentType: "application/json;charset=UTF-8",
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        data: JSON.stringify({
            "operateUserId": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
            "operateUserName": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
            "mainCustomerId": mainCustomerIds,
            "productAppointRuleDtos": productAppointRuleDtosarr
        }),
        success: function (data) {
            if (data.errorCode == 0) {
                $.Huimodalalert('移除成功！', 2000);
                $("#spu_all1").attr("checked", false);
                designatedCommodity();
            } else {
                $.Huimodalalert(data.msg, 2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！', 2000);
        }
    })

};
// 正常商品全部删除
function batchalldelete() {
    var height = ($('#designateddatatable_wrapper').height() / 2) + 100;
    var curInd = layer.confirm(
        '<span>是否全部删除？</span>' + '<br/>', { title: '提示', btn: ['确定', '取消'], offset: height },
        // shieldBatchalldelete(curInd),
        function() {
            $.ajax({
                url: root.member.productAppointRuledeleteAllByCustomerId,
                contentType: "application/json;charset=UTF-8",
                cache: false, //禁用缓存
                type: "POST",
                dataType: 'json',
                data: JSON.stringify({
                    "operateUserId": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
                    "operateUserName": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
                    "mainCustomerId": mainCustomerIds,
                }),
                success: function(data) {
                    if (data.errorCode == 0) {
                        $.Huimodalalert('全部删除成功！', 2000);
                        $("#spu_all1").attr("checked", false);
                        designatedCommodity();
                    } else {
                        $.Huimodalalert(data.msg, 2000);
                    }

                },
                error: function() {
                    $.Huimodalalert('失败！', 2000);
                }
            })
            layer.close(curInd)
        },
        function() {
            layer.close(curInd)
        },
    )

}
//导入
function batchAdding () {
    $("#batchAdding").trigger('click');
};
//批量新增
function batchAddingports () {
    var name = $("#batchAdding").val()
    var result = /\.[^\.]+/.exec(name);
    /* if (result != ".xlsx" && result != ".xls") {
         $.Huimodalalert('格式不正确！',2000);
         return false;
     }*/
    var formData = new FormData();
    formData.append('mainCustomerId', mainCustomerIds);
    formData.append('file', $("#batchAdding")[0].files[0]);
    formData.append('operateUserId', JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID);
    formData.append('operateUserName', JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name);
    $.ajax({
        url: root.member.productAppointRuleimportAppointRuleExcel,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        data: formData,
        success: function (data) {
            console.log(data)
            $('#batchAdding').val('');
            $("#batchAdding").attr('type', 'file');
            if (data.errorCode == 0) {
                $.Huimodalalert('导入成功' + data.data.success_num + '条，失败' + data.data.error_num + '条', 2000);
                designatedCommodity()

            } else {
                $.Huimodalalert(data.msg, 2000);
            }

        }
    });
}
//下载模板
function downloadTemplate () {
    $("#downloadTemplate").attr("href", root.orderInter.downLoadFromUrl + '?urlStr=https://fsyuncai-file.oss-cn-beijing.aliyuncs.com/common/20211031175702254331.xlsx&fileName=指定商品导入模板')
}
//下载错误值
function downloaderrorvalue () {
    $('#downloaderrorvalue').attr('href', root.member.productAppointRuleexport + "?moduleType=10&operateUserId=" + JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID)

}




/*-------------------------------------------------------------------------------------------------------------------------------------------分割线*/

//正常商品列表
getSpecialTypeId();
function getSpecialTypeId () {
    $.ajax({
        url: root.goodsInter.goods_getSpecialSkuTypes,
        cache: false, //禁用缓存
        type: "POST",
        success: function (data) {
            if (data.errorCode == 0) {
                var specialSkuTypesHtml = '<option value="" selected>不限</option><option value="-1">正常商品</option>';
                for (var i = 0; i < data.data.length; i++) {
                    specialSkuTypesHtml += '<option value="' + data.data[i].id + '">' + data.data[i].name + '</option>';
                }
                $(".specialTypeId").html(specialSkuTypesHtml);
            }
        }
    });
}

var dataSource = new Array();
//table的数据源
var table; //table对象
dataSource = [];

function goodsList (data) {
    console.log(data)
    if (dataSource.length > 0) {
        dataSource.splice(0, dataSource.length); //清空数组
    }
    if (data.data.data != null) {
        $.each(data.data.data, function (i, field) {
            var rowData = new Array();
            rowData.push(field.spu_code);
            rowData.push(field.img_url == null ? "" : field.img_url);
            rowData.push(field.spu_name);
            rowData.push(field.subtitile == null ? "" : field.subtitile)
            rowData.push(field.brand_name);
            rowData.push(field.skuPutOnNumber);
            rowData.push(field.spu_id);

            var date = new Date(field.creation_date);
            Y = date.getFullYear() + '-';
            M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
            h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
            m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':';
            s = date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds();

            rowData.push(Y + M + D + h + m + s);
            rowData.push(field.spu_id);
            rowData.push(field.saleAreaId);


            dataSource.push(rowData);
        });
    }

    initDataTable(dataSource);
    function initDataTable (dataSource) {
        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            "autoWidth": false,
            "ordering": true,
            "searching": true,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": [50, 25, 10, 5],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
                "sProcessing": "<img src='./loading.gif' />"
            },
            data: dataSource,
            columnDefs: [{
                "visible": true,
                "targets": 0
            },
            {
                "render": function (data, type, row, meta) {
                    var val = '<span><td>' + row[0] + '</td></span>';
                    return val;
                },
                "targets": 0
            },
            {
                "render": function (data, type, row, meta) {
                    if (row[8] != '') {
                        var val = '<span>' + row[8] + '</span>';
                        return val;
                    } else {
                        var val = '<span></span>';
                        return val;
                    }
                }
                },
                {
                    "render": function(data, type, row, meta) {
                        if(row[7] != '') {
                            var val = '<span>' + row[7] + '</span>';
                            return val;
                        }else {
                            var val = '<span></span>';
                            return val;
                        }
                    },
                    "targets": 6
                },

            {
                "render": function (data, type, row, meta) {
                    if (row[1] != '') {
                        var val = '<span id="spuImg1" ><img onclick="picShow(\'查看图片\',\'picShow.html\',\'' + row[1] + '\')" src="' + row[1] + '" width="80" height="40"></span>';
                        return val;
                    } else {
                        var val = '<span></span>';
                        return val;
                    }
                },
                "targets": 1
            },
            {
                "render": function (data, type, row, meta) {
                    var val = '<span class="shun_text2" style="cursor:pointer;"  title="' + row[3] + '">' + row[3] + '</span>';
                    return val;
                },
                "targets": 3
            },

            ],
            "fnInitComplete": function (oSettings, json) {
                setBtnDis(0, $("#productManage"));
                $("#datatable").on("change", '.spuId', function () {
                    var num = $(".shun").find("input[type=checkbox]:checked").length;
                    setBtnDis(num, $("#productManage"));
                });
            }
        });
        //权限控制函数
        power()
    };
}

function goods_listCategory (categoryLevel) {
    var categoryName = $("#class1").val();
    var user_data = {
        categoryLevel: categoryLevel,
        categoryName: $("#class1").val(),
    }
    var succCallBack = function (data, status, response) {
        console.log(data)
        if (data.errorCode == "0") {
            if (data.data == null) {
                classStr = "<li>无数据</li>"
                $("#classUl1").html(classStr);
            } else {
                var classStr = "";
                for (var i = 0; i < data.data.length; i++) {
                    classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                }
                $("#classUl1").html(classStr);
            }
        }
    }
    web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}

//获取光标
$("#class1").click(function () {
    $("#classUl1").show();
    goods_listCategory(1);
});
$(document).bind("click", function (e) {
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if ($(e.target).closest("#classUl1").length == 0 && $(e.target).closest("#class1").length == 0) {
        //点击id为menu之外且id不是不是open，则触发
        $("#classUl1").hide()
        $("#class2").val();

    }
});
var goodslist_cantegory_id; //定义分类搜索条件

var firstCategoryId;
var secondCategoryId;
var thirdCategoryId;
var fourthCategoryId;

// 2,3,4级的模糊查询
function getNext_input (level, category_id) {
    if (level == 4) {
        goodslist_cantegory_id = category_id;
        thirdCategoryId = category_id;
    }else if(level == 5) {
        fourthCategoryId = category_id;
    }
    if (level < 4) {
        console.log(level)
        $("#class" + level + "")[0].oninput = function () {
            var user_data = {
                parentCateId: category_id,
                categoryName: $("#class" + level + "").val()
            }
            var succCallBack = function (data, status, response) {
                if (data.errorCode == 0) {
                    if (data.data == null) {
                        classStr = "<li>无数据</li>";
                    } else {
                        var classStr = "";
                        for (var i = 0; i < data.data.length; i++) {
                            classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                        }
                    }
                    if (data.data[0] == undefined) {
                        classValue = category_id;
                        var nextLevel = level + 1;
                        $("#classUl" + nextLevel + "").html(classStr);
                        $("#classUl" + level + "").hide();
                    } else {
                        var nextLevel = data.data[0].category_level;
                        $("#classUl" + nextLevel + "").html(classStr);
                        $("#classUl" + level + "").show();
                    }
                }
            }
            web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
        }
        //获取光标
        $("#class" + level + "").focus(function () {
            $("#classUl" + level + "").show();
        });
        $(document).bind("click", function (e) {
            //id为menu的是菜单，id为open的是打开菜单的按钮
            if ($(e.target).closest("#classUl" + level + "").length == 0 && $(e.target).closest("#class" + level + "").length == 0) {
                //点击id为menu之外且id不是不是open，则触发
                $("#classUl" + level + "").hide()
            }
        });
    }

}

function nextClass (category_id, level, category_name) {
    $("#class" + level + "").val(category_name);
    if (level == 1) {
        firstCategoryId = category_id;
        $("#class2").val("");
        $("#class3").val("");
		$("#class4").val("");
    } else if (level == 2) {
	
        secondCategoryId = category_id;
        $("#class3").val("");
        $("#class4").val("");
    }
    var user_data = {
        parentCateId: category_id,
    }
    var succCallBack = function (data, status, response) {
        console.log(data)
        if (data.errorCode == "0") {
            if (data.data == null) {
                classStr = "<li>无数据</li>";
            } else {
                var classStr = "";
                for (var i = 0; i < data.data.length; i++) {
                    classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                }
            }
            if (data.data[0] == undefined) {
                classValue = category_id;
                var nextLevel = level + 1;
                $("#classUl" + nextLevel + "").html(classStr);
                $("#classUl" + level + "").hide();
            } else {
                var nextLevel = data.data[0].category_level;
                $("#classUl" + nextLevel + "").html(classStr);
                $("#classUl" + nextLevel + "").show();
                $("#classUl" + level + "").hide()
            }
        }
    }
    getNext_input(level + 1, category_id);
    web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}


function reloadSpuTable () {
    var customerType = $("input:checkbox[name='customerType']:checked").map(function (index, elem) {
        return $(elem).val();
    }).get().join(',');

    if (customerType.indexOf("1") > -1 && customerType.indexOf("2") > -1) {
        customerType = 3;
    }
    var saleMsg = $("input:checkbox[name='saleArea']:checked").map(function (index, elem) {
        return $(elem).val();
    }).get().join(',');
    if (saleMsg == "" || saleMsg == undefined || saleMsg == null) {
        saleMsg = -1;
    }

    var categoryName = $("#class3").val();
    var firstCategoryName = $("#class1").val();
    var secondCategoryName = $("#class2").val();
    var fourthCategoryName = $("#class4").val();
    if(categoryName == "" || categoryName == undefined || categoryName == null){
        goodslist_cantegory_id = null;
        thirdCategoryId = null;
    }

    if (firstCategoryName == "" || firstCategoryName == undefined || firstCategoryName == null) {
        firstCategoryId = null;
    }

    if (secondCategoryName == "" || secondCategoryName == undefined || secondCategoryName == null) {
        secondCategoryId = null;
    }
    if(fourthCategoryName == "" || fourthCategoryName == undefined || fourthCategoryName == null){
        fourthCategoryId = null;
    }

    $.ajax({
        contentType: 'application/json',
        url: root.member.productPoollistPage,
        cache: false, //禁用缓存
        type: "POST",
        data: JSON.stringify({
            "mainCustomerId": mainCustomerIds,
            firstCategoryId: firstCategoryId,
            secondCategoryId: secondCategoryId,
            thirdCategoryId: goodslist_cantegory_id,
			fourthCategoryId:fourthCategoryId,
            spuCode: $("#spu_code").val(),
            spuName: $("#goodsName").val(),
            skuCode: $("#Code").val(),
            aliasName: $("#aliasParam").val(),
            restricted: $("#isLimitCategory ").val(),
            helpcode: $("#helpcode").val(),
            standards: $("#spuStandards ").val(),
            customerType: customerType,
            brandName: $("#brandName").val(),
            creationDateBegin: $("#creationDateBegin").val(),
            creationDateEnd: $("#creationDateEnd").val(),
            saleArea: saleMsg,
            specialTypeId: $(".specialTypeId").val(),
            proUseable: $("#proUseable").val(),
            pageSize: 50,
            pageNum: 1,
        }),
        success: function (data) {
            goodsList(data);
            $("#spu_all").attr("checked", false);
            var totalPages = 0
            console.log(data.data)
            if (data.data.data != "") {
                totalPages = data.data.pageCount
            } else {
                totalPages = 0
            }
            $('.M-box3').pagination({
                pageCount: totalPages,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    console.log(api.getCurrent());
                    $.ajax({
                        contentType: 'application/json',
                        url: root.member.productPoollistPage,
                        cache: false, //禁用缓存
                        type: "POST",
                        data: JSON.stringify({
                            "mainCustomerId": mainCustomerIds,
                            firstCategoryId: firstCategoryId,
                            secondCategoryId: secondCategoryId,
                            thirdCategoryId: goodslist_cantegory_id,
 							fourthCategoryId:fourthCategoryId,
                            spuCode: $("#spu_code").val(),
                            spuName: $("#goodsName").val(),
                            skuCode: $("#Code").val(),
                            aliasName: $("#aliasParam").val(),
                            restricted: $("#isLimitCategory ").val(),
                            helpcode: $("#helpcode").val(),
                            standards: $("#spuStandards ").val(),
                            customerType: customerType,
                            brandName: $("#brandName").val(),
                            creationDateBegin: $("#creationDateBegin").val(),
                            creationDateEnd: $("#creationDateEnd").val(),
                            saleArea: saleMsg,
                            specialTypeId: $(".specialTypeId").val(),
                            proUseable: $("#proUseable").val(),
                            pageSize: 50,
                            pageNum: api.getCurrent(),
                        }),
                        success: function (data) {
                            goodsList(data);
                            $("#spu_all").attr("checked", false);
                        }
                    });
                }
            });
        }
    });
}
function picShow (title, url, imgUrl) {
    window.event ? window.event.cancelBubble = true : e.stopPropagation();
    sessionStorage.setItem("imgUrlsss", imgUrl);
    layer_show(title, url, "800", "500");
}
function setBtnDis (num, pnode) { //如果选中项为空时，置灰相关按钮
    if (num <= 0) {
        pnode.find(".goods_edit").attr("disabled", "disabled").addClass("dis_btn");
    } else {
        pnode.find(".goods_edit").removeAttr("disabled").removeClass("dis_btn");
    }
}

//全选全不选
function goodselection () {
    if ($("#saleAreas").is(':checked') == true) {
        var saleArea = $("input:checkbox[name='saleArea']")
        for (var i = 0; i < saleArea.length; i++) {
            saleArea[i].checked = true;
        }
    } else {
        var saleArea = $("input:checkbox[name='saleArea']")
        for (var i = 0; i < saleArea.length; i++) {
            saleArea[i].checked = false;
        }
    }

}
//子级选中
goodselectionall()
function goodselectionall () {
    var saleArea = $("input:checkbox[name='saleArea']")
    var saleArea2 = $("input:checkbox[name='saleArea']:checked")
    if (saleArea2.length == saleArea.length) {
        $("#saleAreas").prop("checked", true)
    } else {
        $("#saleAreas").prop("checked", false)
    }
}

//----------------------------------------------------------------------屏蔽正常商品--------------------------------------------------------------------

var shieldr_DataSource = [];

function productShieldRulePageList () {
    $(".dataTables_wrapper_shield").css({
        display: "inline"
    });
    $.ajax({
        url: root.member.productShieldRulelistPage,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify({
            pageNum: 1,
            pageSize: 20,
            mainCustomerId: mainCustomerIds,
            spuCode: $("input[name='spuCode']").val(),
            skuCode: $("input[name='skuCode']").val(),
            skuName: $("input[name='skuName']").val()

        }),
        success: function (result) {
            shieldDesignatedCommoditylist(result);
            $('.M-box3_Shield').pagination({
                pageCount: result.data.pageCount,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        url: root.member.productShieldRulelistPage,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType: 'json',
                        contentType: "application/json",
                        data: JSON.stringify({
                            pageNum: api.getCurrent(),
                            pageSize: 20,
                            mainCustomerId: mainCustomerIds,
                            spuCode: $("input[name='spuCode']").val(),
                            skuCode: $("input[name='skuCode']").val(),
                            skuName: $("input[name='skuName']").val()

                        }),
                        success: function (result) {
                            shieldDesignatedCommoditylist(result);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！', 2000);
        }
    });
}

//屏蔽指定商品列表渲染
function shieldDesignatedCommoditylist (data) {
    console.log(data)
    shieldr_DataSource.splice(0, shieldr_DataSource.length);//清空数组
    if (data.data.data != "") {
        $.each(data.data.data, function (i, field) {
            var rowData = new Array();
            rowData.push(field.productShieldRuleId);
            rowData.push(field.spuCode);
            rowData.push(field.skuCode);
            rowData.push(field.skuName);
            rowData.push(field.operateUserName);
            rowData.push(field.updateTime);
            shieldr_DataSource.push(rowData);
        });
    }
    initDataTable_Shield(shieldr_DataSource);

    //权限控制函数
    power()
}

//初始化屏蔽指定商品Table
function initDataTable_Shield (dataSource) {
    var dttable = $('#productShieldRule_dataTable').dataTable(); // 初始化dataTable，清空上一个值
    dttable.fnClearTable(); //清空一下table
    dttable.fnDestroy(); //还原初始化了的datatable
    $("#productShieldRule_dataTable").DataTable({
        "order": [[1, "desc"]],
        "autoWidth": false,
        "ordering": false,
        "searching": false,
        "paging": false,
        "retrieve": true,
        "destroy": true,
        "bAutoWidth": true,
        "bLengthChange": true,
        "aLengthMenu": [5, 10, 25, 50],
        "oLanguage": {
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "抱歉， 没有找到",
            "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
            "sInfoEmpty": "",
            "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            },
            "sZeroRecords": "没有检索到数据",
            "sProcessing": "<img src='./loading.gif' />",
        },
        data: dataSource,
        columnDefs: [
            {
                "visible": true,
                "targets": 0
            },
            {
                "render": function (data, type, row, meta) {
                    var val = '<span style="text-align: left;"><td><input class="shieldSpuId" type="checkbox" name="shieldSpuId" data-code="' + row[1] + '" data-name="' + row[3] + '" value = "' + row[0] + '">' + row[1] + '</td></span>';
                    return val;
                },
                "targets": 0
            },
            {
                "render": function (data, type, row, meta) {
                    var val = row[3]
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 1
            },
            {
                "render": function (data, type, row, meta) {
                    var val = row[2]
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 2
            },
            {
                "render": function (data, type, row, meta) {
                    var val = row[4]
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 3
            },
            {
                "render": function (data, type, row, meta) {
                    var val = row[5]
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 4
            },
            {
                "render": function (data, type, row) {
                    var val = '<span class=""><a onclick="shieldDetaildelete(' + row[0] + ')">移除</a></span>';
                    return val;
                },
                "targets": 5
            }
        ],
        "fnInitComplete": function (oSettings, json) {
            setBtnDis(0, $("#productManage"));
            $("#productShieldRule_dataTable").on("change", '.shieldSpuId', function () {
                var num = $("#shield_Shun").find("input[type=checkbox]:checked").length;
                setBtnDis(num, $("#productManage"));
            });

        }
    });
};

//单个删除
function shieldDetaildelete (id, code, name) {

    var productShieldRuleIds = [];
    productShieldRuleIds[0] = id;
    $.ajax({
        url: root.member.productShieldRuledeleteBatchByIds,
        contentType: "application/json;charset=UTF-8",
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        data: JSON.stringify({
            "operateUserId": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
            "operateUserName": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
            "mainCustomerId": mainCustomerIds,
            "productShieldRuleIds": productShieldRuleIds
        }),
        success: function (data) {
            if (data.errorCode == 0) {
                $.Huimodalalert('移除成功！', 2000);
                productShieldRulePageList();
            } else {
                $.Huimodalalert(data.msg, 2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！', 2000);
        }
    })
}
//批量删除
function shieldBatchdelete () {

    var productShieldRuleIds = [];
    var spuIdArr = document.getElementsByName('shieldSpuId');
    for (var i = 0; i < spuIdArr.length; i++) {
        if (spuIdArr[i].checked == true) {
            productShieldRuleIds.push(spuIdArr[i].value);
        }
    }
    if (productShieldRuleIds.length < 1) {
        $.Huimodalalert('请选择批量选择数据！', 2000);
        return false;
    }
    $.ajax({
        url: root.member.productShieldRuledeleteBatchByIds,
        contentType: "application/json;charset=UTF-8",
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        data: JSON.stringify({
            "operateUserId": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
            "operateUserName": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
            "mainCustomerId": mainCustomerIds,
            "productShieldRuleIds": productShieldRuleIds
        }),
        success: function (data) {
            if (data.errorCode == 0) {
                $.Huimodalalert('移除成功！', 2000);
                $("#shield_Spu_all").attr("checked", false);
                productShieldRulePageList();
            } else {
                $.Huimodalalert(data.msg, 2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！', 2000);
        }
    })

}
// 屏蔽商品全部删除
function shieldBatchalldelete() {
    var height = ($('#productShieldRule_dataTable_wrapper').height() / 2) + 100;
    var curInd = layer.confirm(
        '<span>是否全部删除？</span>' + '<br/>', { title: '提示', btn: ['确定', '取消'], offset: height },
        // shieldBatchalldelete(curInd),
        function() {
            $.ajax({
                url: root.member.productShieldRuledeleteAllByCustomerId,
                contentType: "application/json;charset=UTF-8",
                cache: false, //禁用缓存
                type: "POST",
                dataType: 'json',
                data: JSON.stringify({
                    "operateUserId": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
                    "operateUserName": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
                    "mainCustomerId": mainCustomerIds,
                }),
                success: function(data) {
                    if (data.errorCode == 0) {
                        $.Huimodalalert('全部删除成功！', 2000);
                        $("#shield_Spu_all").attr("checked", false);
                        productShieldRulePageList();
                    } else {
                        $.Huimodalalert(data.msg, 2000);
                    }

                },
                error: function() {

                    $.Huimodalalert('失败！', 2000);
                }
            })
            layer.close(curInd)
        },
        function() {
            layer.close(curInd)
        },
    )

}
//导入
function shieldBatchAdding () {
    $("#shieldBatchAdding").trigger('click');
}
//批量新增
function shieldBatchAddingports () {
    var name = $("#shieldBatchAdding").val()
    var result = /\.[^\.]+/.exec(name);
    /* if (result != ".xlsx" && result != ".xls") {
         $.Huimodalalert('格式不正确！',2000);
         return false;
     }*/
    var formData = new FormData();
    formData.append('mainCustomerId', mainCustomerIds);
    formData.append('file', $("#shieldBatchAdding")[0].files[0]);
    formData.append('operateUserId', JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID);
    formData.append('operateUserName', JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name);
    $.ajax({
        url: root.member.importShieldRuleExcel,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        data: formData,
        success: function (data) {
            console.log(data)
            $('#shieldBatchAdding').val('');
            $("#shieldBatchAdding").attr('type', 'file');
            if (data.errorCode == 0) {
                $.Huimodalalert('导入成功' + data.data.success_num + '条，失败' + data.data.error_num + '条', 2000);
                productShieldRulePageList()

            } else {
                $.Huimodalalert(data.msg, 2000);
            }

        }
    });
}
//下载模板
function shieldDownloadTemplate () {
    $("#shieldDownloadTemplate").attr("href", root.publics.downLoadFromUrl + '?urlStr=https://fsyuncai-file.oss-cn-beijing.aliyuncs.com/common/20210719173435317984.xlsx&fileName=屏蔽指定商品导入模板')


}
//下载错误值
function shieldDownloaderrorvalue () {
    $('#shieldDownloaderrorvalue').attr('href', root.member.productAppointRuleexport + "?moduleType=60&operateUserId=" + JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID)

}

$(function () {
    $("#shield_Spu_all").click(function () {
        var all_check = $("#shield_Spu_all").is(":checked");
        var spuIds = $(".shieldSpuId");
        for (var i = 0; i < spuIds.length; i++) {
            spuIds[i].checked = all_check;
        }
    })

})
